package com.wuhenzhizao;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.wuhenzhizao.bean.Product;
import com.wuhenzhizao.sku.bean.Sku;
import com.wuhenzhizao.sku.bean.SkuAttribute;
import com.wuhenzhizao.sku.utils.NumberUtils;
import com.wuhenzhizao.sku.view.OnSkuListener;
import com.wuhenzhizao.sku.view.SkuSelectScrollView;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.miscservices.inputmethod.EditingText;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 商品弹窗
 *
 * @author wuhenzhizao
 * @since 2017-08-02
 */
public class ProductSkuDialog extends CommonDialog {
    private static final int TWO_THOUSAND = 2000;
    private static final int ONE_HUNDRED = 100;
    private static final String DIAGONAL_LINE = "\"";
    private static final String SELECT_PLEASE = "请选择：";

    private HiLogLabel logLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, ProductSkuDialog.class.getSimpleName());
    private Context context;
    private Product product;
    private List<Sku> skuList;
    private Callback callback;

    private Sku selectedSku;
    private String priceFormat;
    private String stockQuantityFormat;

    private TextField etSkuQuantityInput;
    private Text btnSkuQuantityMinus;
    private Text btnSkuQuantityPlus;

    /**
     * sku 视图
     */
    private SkuSelectScrollView scrollSkuList;
    /**
     * 商品图
     */
    private Image ivSkuLogo;
    private Button btnSubmit;
    /**
     * 根布局
     */
    private Component parse;

    /**
     * 库存数量
     */
    private Text tvSkuQuantity;
    /**
     * 商品信息展示
     */
    private Text tvSkuInfo;

    /**
     * 构造
     *
     * @param context
     */
    public ProductSkuDialog(Context context) {
        super(context);
        this.context = context;
        initView();
    }

    private void initView() {
        setTransparent(true);
        parse = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_product_sku, null, false);
        setSize(DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        if (getContentCustomComponent() == null) {
            setContentCustomComponent(parse);
        }

        etSkuQuantityInput = (TextField) parse.findComponentById(ResourceTable.Id_et_sku_quantity_input);

        scrollSkuList = (SkuSelectScrollView) parse.findComponentById(ResourceTable.Id_scroll_sku_list);
        ivSkuLogo = (Image) parse.findComponentById(ResourceTable.Id_iv_sku_logo);
        tvSkuQuantity = (Text) parse.findComponentById(ResourceTable.Id_tv_sku_quantity);
        tvSkuInfo = (Text) parse.findComponentById(ResourceTable.Id_tv_sku_info);
        btnSubmit = (Button) parse.findComponentById(ResourceTable.Id_btn_submit);

        initSkuSelectScrollViewListener();
        initSkuQuantityListener();
        initInputListener();

        ivSkuLogo.setScaleMode(Image.ScaleMode.STRETCH);

        parse.findComponentById(ResourceTable.Id_ib_sku_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                hide();
            }
        });

        btnSubmit.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HiLog.error(logLabel, "点击添加");

                String quantity = etSkuQuantityInput.getText();
                if (quantity == null) {
                    return;
                }
                if (isNumber(quantity)) {
                    int quantityInt = Integer.parseInt(quantity);
                    if (quantityInt > 0 && quantityInt <= selectedSku.getStockQuantity()) {
                        callback.onAdded(selectedSku, quantityInt);
                        hide();
                    } else {
                        new ToastDialog(context).setText("商品数量超出库存，请修改数量").setDuration(TWO_THOUSAND).show();
                    }
                } else {
                    showToast();
                }
            }
        });
    }

    private void initInputListener() {
        etSkuQuantityInput.setEditorActionListener(new Text.EditorActionListener() {
            @Override
            public boolean onTextEditorAction(int actionId) {
                if (actionId != EditingText.FLAG_SELECTING || selectedSku == null) {
                    return false;
                }
                String quantity = etSkuQuantityInput.getText();
                if (quantity == null) {
                    return false;
                }
                if (isNumber(quantity)) {
                    HiLog.error(logLabel, "TAG===========" + quantity);
                    int quantityInt = Integer.parseInt(quantity);
                    if (quantityInt <= 1) {
                        etSkuQuantityInput.setText("1");
                        etSkuQuantityInput.setSelected(true);
//                    etSkuQuantityInput.setSelection(1);
                        updateQuantityOperator(1);
                    } else if (quantityInt >= selectedSku.getStockQuantity()) {
                        String newQuantity = String.valueOf(selectedSku.getStockQuantity());
                        etSkuQuantityInput.setText(newQuantity);
//                    etSkuQuantityInput.setSelection(newQuantity.length());
                        etSkuQuantityInput.setSelected(true);
                        updateQuantityOperator(selectedSku.getStockQuantity());
                    } else {
//                    etSkuQuantityInput.setSelection(quantity.length());
                        etSkuQuantityInput.setSelected(true);
                        updateQuantityOperator(quantityInt);
                    }
                } else {
                    showToast();
                }
                return false;
            }
        });
    }

    private void initSkuQuantityListener() {
        btnSkuQuantityPlus = (Text) parse.findComponentById(ResourceTable.Id_btn_sku_quantity_plus);
        btnSkuQuantityPlus.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String quantity = etSkuQuantityInput.getText();
                if (quantity == null || selectedSku == null) {
                    return;
                }
                if (isNumber(quantity)) {
                    int quantityInt = Integer.parseInt(quantity);
                    if (quantityInt < selectedSku.getStockQuantity()) {
                        String newQuantity = String.valueOf(quantityInt + 1);
                        etSkuQuantityInput.setText(newQuantity);
//                    etSkuQuantityInput.setSelection(newQuantity.length());
                        etSkuQuantityInput.setSelected(true);
                        updateQuantityOperator(quantityInt + 1);
                    }
                } else {
                    showToast();
                }
            }
        });

        btnSkuQuantityMinus = (Text) parse.findComponentById(ResourceTable.Id_btn_sku_quantity_minus);
        btnSkuQuantityMinus.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String quantity = etSkuQuantityInput.getText();
                if (quantity == null) {
                    return;
                }
                if (isNumber(quantity)) {
                    int quantityInt = Integer.parseInt(quantity);
                    if (quantityInt > 1) {
                        String newQuantity = String.valueOf(quantityInt - 1);
                        etSkuQuantityInput.setText(newQuantity);
//                    etSkuQuantityInput.setSelection(newQuantity.length());
                        etSkuQuantityInput.setSelected(true);
                        updateQuantityOperator(quantityInt - 1);
                    }
                } else {
                    showToast();
                }
            }
        });
    }

    private void initSkuSelectScrollViewListener() {
        scrollSkuList.setListener(new OnSkuListener() {
            @Override
            public void onUnselected(SkuAttribute unselectedAttribute) {
                HiLog.error(logLabel, "onUnselected");

                selectedSku = null;

                Glide.with(context)
                        .load(product.getMainImage())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .skipMemoryCache(false)
                        .into(ivSkuLogo);

                tvSkuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                tvSkuInfo.setText(SELECT_PLEASE + firstUnselectedAttributeName);
                ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_sku_button);
                shapeElement.setShape(ShapeElement.RECTANGLE);
                btnSubmit.setBackground(shapeElement);
                btnSubmit.setEnabled(false);
                String quantity = etSkuQuantityInput.getText();
                if (quantity != null) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }

            @Override
            public void onSelect(SkuAttribute selectAttribute) {
                HiLog.error(logLabel, "onSelect");

                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                tvSkuInfo.setText(SELECT_PLEASE + firstUnselectedAttributeName);
            }

            @Override
            public void onSkuSelected(Sku sku) {
                HiLog.error(logLabel, "onSkuSelected--" + sku.getMainImage());
                selectedSku = sku;

                Glide.with(context)
                        .load(selectedSku.getMainImage())
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .skipMemoryCache(false)
                        .into(ivSkuLogo);

                List<SkuAttribute> attributeList = selectedSku.getAttributes();
                StringBuilder builder = new StringBuilder();
                for (int i1 = 0; i1 < attributeList.size(); i1++) {
                    if (i1 != 0) {
                        builder.append("　");
                    }
                    SkuAttribute attribute = attributeList.get(i1);
                    builder.append(DIAGONAL_LINE + attribute.getValue() + DIAGONAL_LINE);
                }
                tvSkuInfo.setText("已选：" + builder.toString());
                tvSkuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStockQuantity()));
                ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_sku_item1);
                shapeElement.setShape(ShapeElement.RECTANGLE);
                btnSubmit.setBackground(shapeElement);
                btnSubmit.setEnabled(true);
                String quantity = etSkuQuantityInput.getText().toString();
                updateQuantityOperator(Integer.valueOf(quantity));
            }
        });
    }

    /**
     * 设置商品数据
     *
     * @param product
     * @param callback
     */
    public void setData(final Product product, Callback callback) {
        HiLog.error(logLabel, "---setData");

        this.product = product;
        this.skuList = product.getSkus();
        this.callback = callback;

        priceFormat = context.getString(ResourceTable.String_comm_price_format);
        stockQuantityFormat = context.getString(ResourceTable.String_product_detail_sku_stock);

        updateSkuData();
        updateQuantityOperator(1);
    }

    private void updateSkuData() {
        HiLog.error(logLabel, "1----" + new Gson().toJson(product.getSkus()));
        scrollSkuList.setSkuList(product.getSkus());

        Text tvSkuSellingPrice = (Text) parse.findComponentById(ResourceTable.Id_tv_sku_selling_price);
        Text tvSkuSellingPriceUnit = (Text) parse.findComponentById(ResourceTable.Id_tv_sku_selling_price_unit);
        tvSkuQuantity = (Text) parse.findComponentById(ResourceTable.Id_tv_sku_quantity);

        ivSkuLogo = (Image) parse.findComponentById(ResourceTable.Id_iv_sku_logo);

        Sku firstSku = product.getSkus().get(0);
        if (firstSku.getStockQuantity() > 0) {
            selectedSku = firstSku;
            /**
             * 选中第一个sku
             */
            scrollSkuList.setSelectedSku(selectedSku);

            Glide.with(context)
                    .load(selectedSku.getMainImage())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .skipMemoryCache(false)
                    .into(ivSkuLogo);

            tvSkuSellingPrice.setText(String.format(priceFormat,
                    NumberUtils.formatNumber((double) selectedSku.getSellingPrice() / ONE_HUNDRED)));
            tvSkuSellingPriceUnit.setText("/" + product.getMeasurementUnit());
            tvSkuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStockQuantity()));
            ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_sku_item1);
            shapeElement.setShape(ShapeElement.RECTANGLE);
            btnSubmit.setBackground(shapeElement);
            btnSubmit.setEnabled(selectedSku.getStockQuantity() > 0);
            List<SkuAttribute> attributeList = selectedSku.getAttributes();
            StringBuilder builder = new StringBuilder();
            for (int i1 = 0; i1 < attributeList.size(); i1++) {
                if (i1 != 0) {
                    builder.append("　");
                }
                SkuAttribute attribute = attributeList.get(i1);
                builder.append(DIAGONAL_LINE + attribute.getValue() + DIAGONAL_LINE);
            }
            tvSkuInfo.setText("已选：" + builder.toString());
        } else {
            Glide.with(context)
                    .load(product.getMainImage())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .skipMemoryCache(false)
                    .into(ivSkuLogo);

            tvSkuSellingPrice.setText(String.format(priceFormat,
                    NumberUtils.formatNumber((double) product.getSellingPrice() / ONE_HUNDRED)));
            tvSkuSellingPriceUnit.setText("/" + product.getMeasurementUnit());
            tvSkuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
            ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_sku_button);
            shapeElement.setShape(ShapeElement.RECTANGLE);
            btnSubmit.setBackground(shapeElement);
            btnSubmit.setEnabled(false);
            tvSkuInfo.setText(SELECT_PLEASE + skuList.get(0).getAttributes().get(0).getKey());
        }
    }

    private void updateQuantityOperator(int newQuantity) {
        if (selectedSku == null) {
            btnSkuQuantityMinus.setEnabled(false);
            btnSkuQuantityPlus.setEnabled(false);
            etSkuQuantityInput.setEnabled(false);
        } else {
            if (newQuantity <= 1) {
                btnSkuQuantityMinus.setEnabled(false);
                btnSkuQuantityPlus.setEnabled(true);
            } else if (newQuantity >= selectedSku.getStockQuantity()) {
                btnSkuQuantityMinus.setEnabled(true);
                btnSkuQuantityPlus.setEnabled(false);
            } else {
                btnSkuQuantityMinus.setEnabled(true);
                btnSkuQuantityPlus.setEnabled(true);
            }
            etSkuQuantityInput.setEnabled(true);
        }
    }

    /**
     * 是否为数字
     *
     * @param num 字符串
     * @return 是否
     */
    public boolean isNumber(String num) {
        boolean isNums = false;
        Pattern pattern = Pattern.compile("^[0-9][0-9]*$");
        Matcher isNum = pattern.matcher(num);
        if (isNum.matches()) {
            isNums = true;
        }
        return isNums;
    }

    private void showToast() {
        ToastDialog toastDialog = new ToastDialog(context);
        toastDialog.setText("请输入有效数字").setAlignment(1).setDuration(TWO_THOUSAND).show();
    }


    /**
     * 添加商品回调
     *
     * @since 2017-08-02
     */
    public interface Callback {
        /**
         * 添加商品
         *
         * @param sku
         * @param quantity
         */
        void onAdded(Sku sku, int quantity);
    }
}
